var CryptoJS = require('../utils/tripledes.js');

var pwd = 'zsdlRiYing';  //这里需要传入8个字节以上的密钥
var iv = '20200820'; //偏移量
//加密
function encrypt(val) {
  var encryptData = encryptByDESModeCBCUtf8to64(val, pwd, iv);
  return encryptData;
}

function decode(val){
  var decodestr = decryptByDESModeCBC(val, pwd,iv);
  return decodestr;
}

function encryptByDESModeCBCUtf8to64(message, key, iv) {
  var keyHex = CryptoJS.enc.Utf8.parse(key);
  var ivHex = CryptoJS.enc.Utf8.parse(iv);
  var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
    iv: ivHex,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.ciphertext.toString(CryptoJS.enc.Base64);
}

//CBC模式解密
function decryptByDESModeCBC(ciphertext2, key, iv) {
  var keyHex = CryptoJS.enc.Utf8.parse(key);
  var ivHex = CryptoJS.enc.Utf8.parse(iv);
  // CryptoJS.enc.Base64.parse(
  // direct decrypt ciphertext
  var decrypted = CryptoJS.DES.decrypt({
    ciphertext: CryptoJS.enc.Base64.parse(ciphertext2)
  }, keyHex, {
      iv: ivHex,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    });
  return decrypted.toString(CryptoJS.enc.Utf8);
}

module.exports = { 
  encrypt: encrypt,
  decode: decode
  }